package com.psbc.redis_study.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.psbc.redis_study.dao.ProductMapper;
import com.psbc.redis_study.model.ProductDO;
import com.psbc.redis_study.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;
    @Override
    public int add(ProductDO productDO) {
        return productMapper.insert(productDO);
    }

    @Override
    @CacheEvict(value = {"product"},key = "#root.args[0]",beforeInvocation = true)
    public int delById(int id) {
        return productMapper.deleteById(id);
    }

    @Override
    //在更新用户的时候，如果需要对结果进行缓存，需要用这个注解
    // @Cacheable  这个注解多用来对查询结果进缓存
    @CachePut(value = {"product"},key = "#productDO.id",cacheManager = "cacheManager1Hour")
    public ProductDO updateById(ProductDO productDO) {
        productMapper.updateById(productDO);
        return productDO;
    }

    @Override
    //@Cacheable(value = {"product"},key = "#root.methodName",cacheManager = "cacheManager1Hour")
    //@Cacheable(value = {"product"},keyGenerator = "springCacheDefaultKeyGenerator",cacheManager = "cacheManager1Hour")
    //@Cacheable(value = {"product"},key = "#root.args[0]",cacheManager = "cacheManager1Hour")
    // @Caching  这个注解可以配置很多个注解，就可以一次生成不同的key对应的缓存结果
    @Caching(
            cacheable = {
                    @Cacheable(value = {"product"},key = "#root.args[0]"),
                    @Cacheable(value = {"product"},key = "#root.methodName")
            },
            put = {
                    @CachePut(value = {"product"},key = "#id",cacheManager = "cacheManager1Hour")
            }
    )
    public ProductDO findById(int id) {
        return productMapper.selectById(id);
    }

    @Override
    @Cacheable(value = "page",key = "#root.methodName+'_'+#page+'_'+#size")
    public Map<String, Object> page(int page, int size) {
        Page pageInfo = new Page(page, size);
        IPage<ProductDO> iPage = productMapper.selectPage(pageInfo, null);
        HashMap<String, Object> map = new HashMap<>(3);
        map.put("total_record",iPage.getTotal());
        map.put("total_page",iPage.getPages());
        map.put("current_data",iPage.getRecords());
        return map;
    }
}
